<script setup lang="ts">
import {reactive, ref } from 'vue'
import AgeSelect from "@/components/select/AgeSelect.vue";
import type { FormInstance, FormRules } from 'element-plus'
import {ElMessage} from 'element-plus'
import {userRules} from "@/utils/validate";
import * as userAPI from '@/api/user'

const registerFormRef = ref<FormInstance>()
const registerForm = reactive({
  username: '',
  password: '',
  userAge: -1,
  userIdCard: '',
  userIncome: 0,
  nickName: '',
  userPhone: '',
  userSex: '男'
})
const registerFormRules = reactive<FormRules>({
  username: userRules.username,
  password: userRules.password,
  userIdCard: userRules.idCard,
  userPhone: userRules.phone,
  userIncome: userRules.userIncome,
  nickName: userRules.nickname
})

const submitRegisterForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      try {
        await userAPI.addUser(registerForm)
        ElMessage.success('注册成功')
        formEl.resetFields()
      }catch (e) {
        return
      }
    }
  })
}
</script>

<template>
  <el-form ref="registerFormRef" :model="registerForm" :rules="registerFormRules" label-width="100px">
    <el-form-item label="账号" prop="username">
      <el-input v-model="registerForm.username"/>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="registerForm.password" show-password/>
    </el-form-item>
    <el-form-item label="昵称" prop="nickName">
      <el-input v-model="registerForm.nickName"/>
    </el-form-item>
    <el-form-item label="年龄">
      <AgeSelect v-model="registerForm.userAge"/>
    </el-form-item>
    <el-form-item label="性别">
      <el-radio-group v-model="registerForm.userSex">
        <el-radio label="男">男</el-radio>
        <el-radio label="女">女</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="身份证号" prop="userIdCard">
      <el-input v-model="registerForm.userIdCard"/>
    </el-form-item>
    <el-form-item label="收入" prop="userIncome">
      <el-input v-model.number="registerForm.userIncome"/>
    </el-form-item>
    <el-form-item label="电话号码" prop="userPhone">
      <el-input v-model="registerForm.userPhone"/>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitRegisterForm(registerFormRef)">注册</el-button>
    </el-form-item>
  </el-form>
</template>

<style lang="less" scoped>
  .el-form {
    margin: 20px auto;
    width: 400px;
  }


  .el-form-item {
    .el-button {
      width: 100%;
    }
  }
</style>